package util.conversor;

import syntaxtree.ArrayAssign;
import syntaxtree.Assign;
import syntaxtree.Block;
import syntaxtree.Exp;
import syntaxtree.Identifier;
import syntaxtree.If;
import syntaxtree.Print;
import syntaxtree.Statement;
import syntaxtree.While;
import util.List;
import minijava.analysis.AnalysisAdapter;
//import minijava.node.AArrayAssignStatement;
//import minijava.node.AAssignStatement;
//import minijava.node.ABlockStatement;
//import minijava.node.AIfStatement;
//import minijava.node.APrintStatement;
//import minijava.node.AWhileStatement;
import minijava.node.AAssignStm;
import minijava.node.ABlockStm;
import minijava.node.AIfStm;
import minijava.node.APrintStm;
import minijava.node.AVectorAssignStm;
import minijava.node.AWhileStm;
import minijava.node.PStm;
import minijava.node.Token;

class StatementHandler extends AnalysisAdapter
{
	private Statement result;
	
	public StatementHandler()
	{
		super();
	}
	
	static Statement convert(PStm node)
	{
		StatementHandler h = new StatementHandler();
		
		node.apply(h);
		
		return h.result;
	}
	@Override
    public void caseABlockStm(ABlockStm node)
    {
    	List<Statement> ss = StatementListHandler.convert(node.getStmList());
    	result = new Block(0, 0, ss);    	
    }
	@Override
    public void caseAWhileStm(AWhileStm node)
    {
    	Exp c = ExpHandler.convert(node.getCondition());
		Statement b = StatementHandler.convert(node.getStm());
		
		result = new While(c.line, c.row, c, b);
    }
	@Override
    public void caseAIfStm(AIfStm node)
    {
    	Exp c = ExpHandler.convert(node.getCondition());
		Statement t = StatementHandler.convert(node.getIfStm());
		Statement e = node.getElseStm() == null ? null : StatementHandler.convert(node.getElseStm());
		
		result = new If(t.line, t.row, c, t, e);
    }
	@Override
    public void caseAPrintStm(APrintStm node)
    {
    	Exp value = ExpHandler.convert(node.getExpression());
		
		result = new Print(value.line, value.row, value);
    }
	@Override
    public void caseAAssignStm(AAssignStm node)
    {
    	Token t = node.getVariable();
    	Exp value = ExpHandler.convert(node.getValueExpression());
    	Identifier id = new Identifier(t.getLine(), t.getPos(), t.getText());
		
		result = new Assign(id.line, id.row, id, value);
    }
	@Override
    public void caseAVectorAssignStm(AVectorAssignStm node)
    {
    	Token t = node.getVectorVariable();
		Exp index = ExpHandler.convert(node.getIndexExpression());
		Exp value = ExpHandler.convert(node.getValueExpression());
		
		Identifier id = new Identifier(t.getLine(), t.getPos(), t.getText());
		
		result = new ArrayAssign(id.line, id.row, id, index, value);	
    }
}
